//    Copyright (C) Kherty.  All rights reserved.

#region

using System;
using System.IO.Packaging;
using OpenLS.Core.Serialization;

#endregion

namespace OpenLS.Spreadsheet
{
    internal class ExternalLink : IOfficeXmlSerializable
    {
        public ExternalLink(int index)
        {
            Index = index;
        }

        public ExternalWorkbook ExternalBook { get; set; }

        public DdeLink DdeLink { get; set; }

        public OleLink OleLink { get; set; }

        public ExtensionElement Extension { get; set; }

        public int Index { get; set; }

        #region IOfficeXmlSerializable Members

        public void ReadXml(ReadContext context)
        {
            using (ReadContext c = context.Read("externalLink"))
            {
                if (c.ReaderLocalName == "externalBook")
                {
                    string rid = c.GetOptionalString(OfficeConstants.RelationshipNamespace + "id");

                    string fileName = null;
                    try
                    {
                        PackageRelationship rel = c.Part.GetRelationship(rid);
                        fileName = rel.TargetUri.ToString();
                    }
                    catch (UriFormatException)
                    {
                        fileName = @"c:\INVALID FILE.XLSX";
                    }
                    SpreadsheetDocument document = SpreadsheetDocument.OpenEmpty(fileName, SpreadsheetContext.Default);
                        //\\

                    ExternalBook = c.ReadOptionalElement("externalBook",
                                                         () => new ExternalWorkbook(this, document));
                }

                DdeLink = c.ReadOptionalElement<DdeLink>("ddeLink");
                OleLink = c.ReadOptionalElement<OleLink>("oleLink");
                Extension = c.ReadOptionalElement<ExtensionElement>("extLst");
            }
        }

        public void WriteXml(WriteContext context)
        {
            using (WriteContext c = context.Write("externalLink"))
            {
                c.WriteOptionalElement(ExternalBook);
                c.WriteOptionalElement(DdeLink);
                c.WriteOptionalElement(OleLink);
                c.WriteOptionalElement(Extension);
            }
        }

        #endregion
    }
}